package com.dataStructure.Linklist;

import com.Excrises.Seven.Employee;

import java.util.LinkedList;

public class MyLinkedList<E> {

    public static void main(String[] args) {

        Employee employee = new Employee();
        employee.setName("luolin");
        Employee employee2 = employee;
        employee2.setName("jjjj");
        System.out.println(employee.getName());
        Employee employee1 = new Employee();
        employee1.setName("luolin");

    }

    /**
     * 节点内部类
     */
    private class Node{
        public E data;
        public Node next;

        public Node(E data, Node next) {
            this.data = data;
            this.next = next;
        }

        public Node(E data) {
            this.data = data;
        }


        public Node() {
        }
    }

    private int size;
    private Node head;


    /**
     * 添加元素到链表的尾部
     * @param object
     * @return
     */
    public boolean add(E object) {
        if (this.head == null) {
            head = new Node(object,null);
        } else {
            Node node = head;
            for (;node.next != null; node = node.next) {
            }
            node.next = new Node(object);
        }
        size++;
        return true;
    }


    /**
     * 查找元素的索引
     * @param object
     * @return
     */
    public int indexOf(E object) {
        Node node = head;
        for (int i = 0;i < size; i++) {
            if (equals(node.data,object)) {
                return i;
            }
            node = node.next;
        }
        return -1;
    }

    /**
     *  利用一行中的代码从右往左执行，  node.next = new Node(object,node.next);
     *
     */
    public void add(int index,E object) {
      if (index == 0) {
          head = new Node(object,head);
      } else {
          Node node = getNode(index - 1);
          //将插入位置的前一位的next指向object，并将object.next指向node.next；
          node.next = new Node(object,node.next);
      }
      size++;
    }


    public E remove(int index) {
        if (index ==0) {
            head = head.next;
        }
        else {
            Node node = getNode(index - 1);
            node.next = node.next.next;
        }
        size --;
        return null;
    }

    /**
     * 获取指定索引的节点
     * @param index
     * @return
     */
    private Node getNode(int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("查出链表容量");
        }
        Node node = head;
        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node;
    }

    private boolean equals(E data, E object) {
        if (object == null) {
            return false;
        } else {
            return object.equals(data);
        }
    }


    /**
     * 清空列表元素
     */
    public void clear() {
        this.head = null;
        size = 0;
    }


    public MyLinkedList() {
        this.size = 0;
        this.head = null;
    }



}
